<?php

/**
 * @param $url
 * @param $mothed
 * @param $contentbody
 * @param $access_token
 * @return bool|string
 */
function curlRequest($url,$mothed, $contentbody,$header='')
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $mothed);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $contentbody);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $temp = curl_exec($ch);
    curl_close($ch);
    return $temp;
}

/**
 * CURL POST 方式获取数据
 * @param $url
 * @param array $data
 * @return bool|string
 */
function curl_raw_post($url,$post_data = array()){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
    curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-Type: application/json'));
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}

/**
 * CURL GET 方式获取数据
 * @param $url
 */
function curl_get($url){
    $info = curl_init();
    curl_setopt($info,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($info,CURLOPT_HEADER,0);
    curl_setopt($info,CURLOPT_NOBODY,0);
    curl_setopt($info,CURLOPT_SSL_VERIFYPEER,false);
    curl_setopt($info,CURLOPT_SSL_VERIFYPEER,false);
    curl_setopt($info,CURLOPT_SSL_VERIFYHOST,false);
    curl_setopt($info,CURLOPT_URL,$url);
    $output = curl_exec($info);
    curl_close($info);
    return $output;
}

/**
 * 获取头条getAccessToken
 */
function touTiaoToken(){
    $appid = config('douyin_appid');
    $appsecret = config('douyin_appsecrect');
    $url = "https://developer.toutiao.com/api/apps/token?appid=".$appid."&secret=".$appsecret."&grant_type=client_credential";
    $data = curl_get($url);
    $data = json_decode($data,true);
    if (isset($data['errcode'])){
        return false;
    }
    return $data;
}

/**
 * 头条内容安全检测
 */
function textAntidirt($tasks=null){
    $tou_tioa_token = touTiaoToken();
    if ($tou_tioa_token==false){
        $this->error('获取token出错');
    }
    $contentbody = '{"tasks": [{"content": "'.$tasks.'"}]}';
    $url = "https://developer.toutiao.com/api/v2/tags/text/antidirt";
    $header = array('X-Token: '.$tou_tioa_token['access_token'].'');
    $respon = curlRequest($url,'POST',$contentbody,$header);
    $data = json_decode($respon,true);

    if (isset($data['code'])){
        $res['code'] = 401;
        return $res;
    }
    if ($data['data'][0]['code']==0){
        if ($data['data'][0]['predicts'][0]['prob']==1){
            $res['code'] = 0;
            return $res;exit;
        }
    }
    $res['code'] = 1;
    return $res;
}

/**
 * 检测图片包含违法违规内容
 * @param null $img
 * @return bool
 */
function imageAntidirt($img=null){
    $tou_tioa_token = touTiaoToken();

    if ($tou_tioa_token==false){
        $this->error('获取token出错');
    }
    $contentbody = '{"targets": ["porn","politics","ad","disgusting"],"tasks": [{"image_data": "'.$img.'"}]}';
    $url = "https://developer.toutiao.com/api/v2/tags/image/";
    $header = array('X-Token: '.$tou_tioa_token['access_token'].'');
    $respon = curlRequest($url,'POST',$contentbody,$header);
    $data = json_decode($respon,true);

    if (isset($data['code'])){
        $res['code'] = 401;
        return $res;
    }
    if ($data['data'][0]['code']==0){
        $predicts = $data['data'][0]['predicts'];
        foreach ($predicts as $k=>$v){

            if ($v['prob']>=0.7){
                $res['code'] = 0;
                return $res;exit;
            }
        }
    }
    $res['code'] = 1;
    return $res;
}

/**
 * 排序
 * @param $arrays
 * @param $sort_key
 * @param int $sort_order
 * @param int $sort_type
 * @return array|bool
 */
function my_sort($arrays,$sort_key,$sort_order=SORT_ASC,$sort_type=SORT_NUMERIC )
{
    if (is_array($arrays)) {
        foreach ($arrays as $array) {
            if (is_array($array)) {
                $key_arrays[] = $array[$sort_key];
            } else {
                return false;
            }
        }
    } else {
        return false;
    }
    array_multisort($key_arrays, $sort_order, $sort_type, $arrays);
    return $arrays;
}

//主动判断是否HTTPS
function isHTTPS()
{
    if (defined('HTTPS') && HTTPS) return true;
    if (!isset($_SERVER)) return FALSE;
    if (!isset($_SERVER['HTTPS'])) return FALSE;
    if ($_SERVER['HTTPS'] === 1) {  //Apache
        return TRUE;
    } elseif ($_SERVER['HTTPS'] === 'on') { //IIS
        return TRUE;
    } elseif ($_SERVER['SERVER_PORT'] == 443) { //其他
        return TRUE;
    }
    return FALSE;
}

/**
 * 获取图片的Base64编码(不支持url)
 * @param $img_file 传入本地图片地址
 * @return string
 */
function imgToBase64($img_file,$suffix) {
    $img_base64 = '';
    if (file_exists($img_file)) {
        $app_img_file = $img_file; // 图片路径
        $img_info = getimagesize($app_img_file); // 取得图片的大小，类型等

        //echo '<pre>' . print_r($img_info, true) . '</pre><br>';
        $fp = fopen($app_img_file, "r"); // 图片是否可读权限

        if ($fp) {
            $filesize = filesize($app_img_file);
            $content = fread($fp, $filesize);
            $file_content = base64_encode($content); // base64编码
            // switch ($img_info[2]) {           //判读图片类型
            //     case 1: $img_type = "gif";
            //         break;
            //     case 2: $img_type = "jpg";
            //         break;
            //     case 3: $img_type = "png";
            //         break;
            // }

            $img_base64 = 'data:image/' . $suffix . ';base64,' . $file_content;//合成图片的base64编码

        }
        fclose($fp);
    }

    return $img_base64; //返回图片的base64
}

/**
 * 126接口：根据ip获取所在城市名称
 */
function get_ip_area($ip)
{
    if ($ip == '127.0.0.1') {
        return '内网IP';
    }
    $url = "http://ip.ws.126.net/ipquery?ip={$ip}";
    $ret = curl_get($url);
    $formatRet = mb_convert_encoding($ret, 'utf-8', 'gbk');
    $temp_addr_array = explode(';', $formatRet);
    $temp1_addr = $temp_addr_array[0];
    $temp_addr_array = explode(',', $temp1_addr);
    $temp1_addr = $temp_addr_array[0];
    $temp2_addr = $temp_addr_array[1];
    $temp_province_array = explode('"', $temp1_addr);
    $temp_city_array = explode('"', $temp2_addr);
    $province = $temp_province_array[1];
    $city = $temp_city_array[1];
    return $province . $city;
}